<template>
     <pageTabelLayout>
      <template #pageHeader>
      <div class="my-header">
        <div class="search-form isheader" v-if="headerShow">
          <div>
            <a-form size="mini" :model="queryData" layout="inline">
              <a-form-item label="所属公司">
                <a-cascader
                  v-model="queryData.firmId"
                  :options="gsDatas"
                  allow-clear
                  class="bacClass"
                  @click="getAllActiveCompany"
                  @change="queryClearChange"
                  :style="{ width: '160px' }"
                  popup-container="html"
                />
              </a-form-item>
              <a-form-item label="仓库名称">
                <a-select popup-container="html" 
                  class="bacClass"
                  :style="{ width: '160px' }"
                  :loading="loading"
                  :filter-option="false"
                  allow-search
                  allow-clear
                  v-model.trim="queryData.warehouseName"
                  @click="handleSearchs"
                >
                  <a-option v-for="item in pageData.warehouseName" :value="item.warehouseName">{{
                    item.warehouseName
                  }}</a-option>
                </a-select>
              </a-form-item>
              <a-form-item label="布笼类型">
                <a-select popup-container="html" 
                  class="bacClass"
                  v-model="queryData.clothType"
                  :style="{ width: '160px' }"
                  allow-search
                  allow-clear
                >
                  <a-option :value="0">通用布笼</a-option>
                  <a-option :value="1">固定布笼</a-option>
                </a-select>
              </a-form-item>
            </a-form>
          </div>
          <div class="my-tool-bar">
            <Toolbar
              :items="[
                `${permissionStore.hasPermisson('blxx.cx') ? '查询' : ''}`,
                `${permissionStore.hasPermisson('blxx.xz') ? '新增' : ''}`,
                `${permissionStore.hasPermisson('blxx.sc') ? '删除' : ''}`,
                `${permissionStore.hasPermisson('blxx.dc') ? '导出' : ''}`,
                '通用布笼模板导入',
                '通用布笼模板下载',
              ]"
              @add="addHandler"
              @del="deleteHandler"
              @select="selectHandler"
              @export="exports"
              @tyblmbxz="tyblmbxzs"
              @imports="importHandler"
            >
            </Toolbar>
          </div>
        </div>
        <div class="my-divisders">
          <a-divider orientation="center">
            <icon-double-up
              v-if="headerShow"
              @click="headerShow = false"
              :strokeWidth="2"
              :size="18"
            />
            <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
          </a-divider>
        </div>
        <!-- <div class="my-tool-bar">
                    <Toolbar :items="['查询', '新增', '删除', '导出']" @add="addHandler" @del="deleteHandler"
                        @select="selectHandler" @export="exports">
                    </Toolbar>
                </div> -->
      </div>
      <div class="gang"></div>
    </template>

    
    <template #pageTabel>
    <a-spin :loading="pageData.pageLoading" style="width: 100%; height: 100%">
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        :suppressDragLeaveHidesColumns="true"
        rowSelection="multiple"
        @grid-ready="gridReady"
        @columnResized="onColumnResized"
        @columnMoved="onColumnMoved"
        @columnVisible="onColumnVisible"
        style="height: calc(100% - 45px);"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="tc"
        :localeText="localeText1"
      >
      </AgGridVuesCopys>
      <paginationCopys
        :page-size-options="pagingList1"
        :page-size="size"
        :current="page"
        :total="total"
        show-total
        show-jumper
        show-page-size
        @change="PageSize"
        @page-size-change="change1"
        style="justify-content: center"
      />
      </a-spin>
    </template>
  <a-drawer
    ok-text="保存"
    cancel-text="关闭"
    :drawer-style="{ zIndex: 9999 }"
    :mask-closable="false"
    :width="400"
    :visible="pageData.showAdd"
    unmountOnClose
    @ok="sideOk"
    @cancel="sideNo"
  >
    <template #title>
      {{ pageData1.sideTitle }}
    </template>
    <div>
      <!-- 所属工厂 仓库名称 联系人 联系电话 地址 -->
      <a-form ref="formRef" :model="dataForm" layout="horizontal">
        <a-form-item
          label="布笼类型"
          field="clothType"
          :rules="[{ required: true, message: '布笼类型必填' }]"
          label-col-flex="80px"
        >
          <a-select popup-container="html"  class="bacClass" v-model="dataForm.clothType" @change="clothTypeChange">
            <a-option :value="0">通用布笼</a-option>
            <a-option :value="1">固定布笼</a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="所属公司"
          v-if="ifalse"
          :rules="[{ required: true, message: '公司必填' }]"
          label-col-flex="80px"
        >
          <a-cascader
            v-model="dataForm.firmId"
            :options="gsDatas"
            allow-clear
            class="bacClass"
            @change="xzgs"
            @click="getAllActiveCompany"
            ref="casOb"
            popup-container="html"
          />
        </a-form-item>
        <a-form-item
          label="仓库类别"
          field="cklb"
          v-if="ifalse"
          :rules="[{ required: true, message: '类别必填' }]"
          label-col-flex="80px"
        >
          <a-select popup-container="html" 
            class="bacClass"
            v-model="dataForm.cklb"
            @click="getAllTypeName"
            @change="clearWarehouseChange"
            allow-clear
          >
            <a-option v-for="item in cklb" :value="item.typeName">{{ item.typeName }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="选择仓库"
          field="warehouseName"
          v-if="ifalse"
          :rules="[{ required: true, message: '仓库必填' }]"
          label-col-flex="80px"
        >
          <a-select popup-container="html" 
            @click="xzlb"
            class="bacClass"
            v-model="dataForm.warehouseName"
            @change="xzckId"
            allow-clear
          >
            <a-option v-for="item in xzck" :value="item.warehouseName"
              >{{ item.warehouseName }}
            </a-option>
          </a-select>
        </a-form-item>
        <!-- <a-form-item label="选择区域" field="areaName">
                    <a-select popup-container="html"  class="bacClass" v-model="dataForm.areaName" allow-clear @change="qyLists">
                        <a-option v-for="item in qyList" :value="item.areaName">{{ item.areaName }}
                        </a-option>
                    </a-select>
                </a-form-item> -->
        <a-form-item
          label="布笼名称"
          field="shelveName"
          :rules="[{ required: true, message: '布笼名称必填' }]"
          label-col-flex="80px"
        >
          <a-input class="bacClass" placeholder="" v-model.trim="dataForm.shelveName" />
        </a-form-item>
        <a-form-item
          label="一维码"
          field="shelveBarCode"
          :rules="[{ validator: isNumber }, { required: true, message: '一维码号码必填' }]"
          label-col-flex="80px"
        >
          <a-input class="bacClass" placeholder="" v-model.trim="dataForm.shelveBarCode" />
        </a-form-item>
        <a-form-item
          label="编号"
          field="shelveCode"
          :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
          label-col-flex="80px"
        >
          <a-input
            class="bacClass"
            placeholder=""
            @blur="inputBlur"
            v-model.trim="dataForm.shelveCode"
          />
        </a-form-item>
        <a-form-item label="备注" field="remark" label-col-flex="80px">
          <a-textarea
            class="bacClass"
            v-model="dataForm.remark"
            :max-length="400"
            allow-clear
            show-word-limit
          />
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
  <ModalDialog :mask-closable="false" ref="qrModal" title="布笼二维码" @confirm="gbModal">
    <template #content>
      <a-space direction="vertical">
        <a-button type="primary" @click="print">打印</a-button>
        <div id="htsts" style="width: 400px">
          <QrcodeVue :value="qrData.code"></QrcodeVue>
          <div style="display: inline-block; vertical-align: top; margin-left: 15px">
            <div v-if="qrData.gcName != ''" style="width: 200px">工厂名称：{{ qrData.gcName }}</div>
            <div v-if="qrData.ckType != ''" style="width: 200px">仓库类型：{{ qrData.ckType }}</div>
            <div v-if="qrData.ckName != ''" style="width: 200px">仓库名称：{{ qrData.ckName }}</div>
            <div style="width: 200px">布笼类型：{{ qrData.clothTypeStr }}</div>
            <div style="width: 200px">布笼名称：{{ qrData.hjName }}</div>
          </div>
        </div>
      </a-space>
    </template>
  </ModalDialog>
  <ModalDialog :mask-closable="false" ref="qrModals" title="储位二维码" @confirm="gbModals">
    <template #content>
      <a-space direction="vertical">
        <a-button type="primary" @click="print1">打印</a-button>
        <div id="hts" style="width: 500px">
          <QrcodeVue :value="qrDatas.code"></QrcodeVue>
          <div style="display: inline-block; vertical-align: top; margin-left: 15px">
            <div style="width: 300px">工厂名称：{{ qrDatas.gcName }}</div>
            <div style="width: 300px">仓库名称：{{ qrDatas.ckName }}</div>
            <div style="width: 300px">布笼名称：{{ qrDatas.hjName }}</div>
            <div style="width: 300px">储位名称：{{ qrDatas.cwName }}</div>
          </div>
        </div>
      </a-space>
    </template>
  </ModalDialog>
  <ModalDialog :mask-closable="false" ref="qrModals1" title="储位二维码" @confirm="gbModals1">
    <template #content>
      <a-space direction="vertical">
        <a-button type="primary" @click="print2">打印</a-button>
        <div id="hts1" style="width: 400px">
          <div v-for="item in qrDatas1 as any">
            <QrcodeVue :value="item.code"></QrcodeVue>
            <div style="display: inline-block; vertical-align: top; margin-left: 15px">
              <div style="width: 200px">工厂名称：{{ item.firm }}</div>
              <div style="width: 200px">仓库名称：{{ item.warehouseName }}</div>
              <div style="width: 200px">布笼名称：{{ item.shelveName }}</div>
              <div style="width: 200px">储位名称：{{ item.storageName }}</div>
            </div>
          </div>
        </div>
      </a-space>
    </template>
  </ModalDialog>
  <a-drawer
    ok-text="关闭"
    :hide-cancel="true"
    :drawer-style="{ zIndex: 999 }"
    :mask-closable="false"
    :width="400"
    popup-container=".main-base-style"
    :height="pageData2.rHeight"
    :visible="pageData2.showAdd"
    placement="bottom"
    unmountOnClose
    @ok="sideNo1"
    :closable="false"
  >
    <template #title> 储位设定 </template>
    <div class="selectCc">
      <a-button status="success" @click="openQRcodes1">储位二维码</a-button>
      <Toolbar :items="['新增', '删除']" @add="addHandler1" @del="delcwTab"> </Toolbar>
    </div>
    <a-table
      size="mini"
      :style="{ height: pageData2.rHeight + 'px' }"
      @page-change="pagination.change"
      :columns="columns"
      :data="dataLists"
      v-model:selected-keys="selectedRowKeys1"
      :rowKey="rowKey"
      :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
    >
      <template #storageName="{ record }">
        <a-input class="bacClass" placeholder="" v-model="record.storageName" />
        <!-- <a-input class="bacClass" v-else disabled placeholder="请输入储位名称" v-model="record.storageName" /> -->
      </template>
      <template #storageCode="{ record }">
        <a-input class="bacClass" placeholder="" v-model="record.storageCode" />
        <!-- <a-input class="bacClass" v-else disabled placeholder="请输入储位自定义代号" v-model="record.storageCode" /> -->
      </template>
      <template #save="{ record }">
        <a-space>
          <a-button type="primary" @click="bcCw(record)">保存</a-button>
          <a-button type="primary" status="warning" @click="bcCw1(record)">
            <template #icon>
              <icon-edit />
            </template>
            修 改
          </a-button>
        </a-space>
      </template>
      <template #qrcodes="{ record }">
        <a-button status="success" @click="openQRcodes(record)">储位二维码</a-button>
      </template>
    </a-table>
  </a-drawer>
  <a-modal
    :visible="visible"
    @ok="modalOk"
    @cancel="modalCancel"
    okText="打印"
    cancelText="关闭"
    unmountOnClose
    draggable
  >
    <template #title>{{ modalData.num == 1 ? '打印一维码' : '打印二维码 ' }} </template>
    <div id="modalprint">
      <QrcodeVue :value="modalData.code" v-if="modalData.num == 2"></QrcodeVue>
      <oneCode v-if="modalData.num == 1&&modalData.code1" :value="modalData.code1"></oneCode>
      <span style="color:red;" v-if="modalData.num == 1&&!modalData.code1">一维码为空，请先维护！</span>
      <div style="display: inline-block; vertical-align: top; margin-left: 15px; width: 250px">
        <span>布笼名称: {{ decodeURI(modalData.shelveName) }}</span>
        <br />
        <span>编号:{{ decodeURI(modalData.shelveCode) }} </span>
        <br />
        <span>创建人: {{ decodeURI(modalData.createName) }}</span>
        <br />
        <span>布笼类型: {{ decodeURI(modalData.clothTypeStr) }}</span>
        <br />
      </div>
    </div>
  </a-modal>
</pageTabelLayout>
</template>

<script lang="ts">
  import { get, post } from '@/api/http'
  import axios from 'axios'

  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import QrcodeVue from 'qrcode.vue'
  import printJS from 'print-js'
  import { ModalDialogType } from '@/types/components'
  import { localeText } from '@/api/aggridZw'
  import { ref, reactive, onMounted, toRefs, defineComponent } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import ModalDialog from '@/components/ModalDialog.vue'
  
  import usePermission from '@/store/modules/permission'
  import { pagingList } from '@/api/paging'
  import oneCode from '@/components/Barcode/index.vue'
  import { baseURL } from '../../../api/axios.config'
  import filedownload from 'js-file-download'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'

  interface Firm {
    name: string
    id: number
  }
  interface Cloth {
    code: string
  }
  interface chuwei {
    id: any
    firm: any
    warehouseId: any
    warehouseName: any
    name: any
    extendCode: any
    cklb: any
    shelveCode: any
    shelveName: any
    firmId: Number | undefined
    remark: any
    areaName: any
    areaId: Number
    clothType: Number
    shelveBarCode: any
  }
  export default {
    name: 'AstorageShelf',
    setup() {
      const permissionStore: any = usePermission()
      const total = ref(10)
      const page = ref(1)
      const size = ref(10)
      const visible = ref(false)
      const modalData:any = ref({
        num: 1,
      })
      function PageSize(val: any) {
        page.value = val
        doRefresh()
      }
      function change1(val: any) {
        size.value = val
        doRefresh()
      }
      function doRefresh() {
        pageData.pageLoading = true
        updateGridState01()
        post({
          url: 'wms/shelve/getShelvePage',
          data: {
            page: page.value,
            size: size.value,
            firmId: queryData.firmId,
            warehouseName: queryData.warehouseName,
            clothType: queryData.clothType,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data.list)
              gridOption.value.setRowData(data.list)
              pagination.setTotalSize(data.total)
              total.value = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }
      const validateIdCheck = (value: any, callback: any) => {
        if (typeof value !== 'number') {
          callback('id为数字')
        }
      }
      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      //假数据后期需要修改
      // const dataList = reactive({
      //     list: [{
      //         id: 1,
      //         code: 1,
      //         mercery_name: '掌紫元',
      //         remark: "WH22101800000002",
      //         remark_1: '裁断中仓',
      //         remark_2: '佛山',
      //         remark_3: '勇哥',
      //         remark_4: '110'
      //     }]
      // })
      let qrModal = ref<ModalDialogType | null>(null)
      const qrData = reactive({
        ckName: '',
        gcName: '',
        code: '',
        hjName: '',
        clothTypeStr: '',
        ckType: '',
      })
      const openQRcode = (item: any) => {
        post({
          url: 'wms/shelve/printShevlve',
          data: [item.id],
        }).then((res: any) => {
          if (res.code == 200) {
            qrData.gcName = res.data[0].firm
            qrData.ckName = res.data[0].warehouseName
            qrData.hjName = res.data[0].shelveName
            qrData.ckType = res.data[0].warehouseTypeName
            if (gridOption.value.getSelectedRows()[0].clothType == 0) {
              qrData.clothTypeStr = '通用布笼'
            } else {
              qrData.clothTypeStr = '固定布笼'
            }
            qrData.code = JSON.stringify({
              shelveId: res.data[0].shelveId,
              warehouseId: res.data[0].warehouseId,
              clothType: res.data[0].clothType,
            })
            qrModal.value?.toggle()
          } else {
            Message.error(res.message)
          }
        })
      }
      const openBarcode = (item: any) => {
        modalData.value.code1 = item.shelveBarCode
        modalData.value.shelveName = item.shelveName
        modalData.value.shelveCode = item.shelveCode
        modalData.value.createName = item.createName
        modalData.value.clothTypeStr = item.clothType===0?'通用布笼':'固定布笼'
        visible.value = true
      }
      const modalOk = () => {
        printJS({
          printable: 'modalprint',
          type: 'html',
          targetStyles: ['*'],
        })
        visible.value = false
      }
      const modalCancel = () => {
        visible.value = false
      }
      let qrModals = ref<ModalDialogType | null>(null)
      const qrDatas = reactive({
        ckName: '',
        gcName: '',
        code: '',
        hjName: '',
        cwName: '',
      })
      const openQRcodes = (item: any) => {
        post({
          url: 'wms/Storage/printStorage',
          data: [item.id],
        }).then((res: any) => {
          if (res.code == 200) {
            qrDatas.gcName = res.data[0].firm
            qrDatas.ckName = res.data[0].warehouseName
            qrDatas.hjName = res.data[0].shelveName
            qrDatas.cwName = res.data[0].storageName
            qrDatas.code = JSON.stringify({
              warehouseId: res.data[0].warehouseId,
              shelveId: res.data[0].shelveId,
              storageId: res.data[0].storageId,
            })
            qrModals.value?.toggle()
          } else {
            Message.error(res.message)
          }
        })
      }
      let qrModals1 = ref<ModalDialogType | null>(null)
      const qrDatas1: any = ref([])
      const openQRcodes1 = () => {
        if (selectedRowKeys1.value.length == 0) {
          Message.warning('请先勾选')
          return
        }
        post({
          url: 'wms/Storage/printStorage',
          data: selectedRowKeys1.value,
        }).then((res: any) => {
          if (res.code == 200) {
            selectedRowKeys1.value = []
            qrDatas1.value = res.data
            for (let i = 0; i < qrDatas1.value.length; i++) {
              qrDatas1.value[i].code = JSON.stringify({
                warehouseId: qrDatas1.value[i].warehouseId,
                shelveId: qrDatas1.value[i].shelveId,
                storageId: qrDatas1.value[i].storageId,
              })
            }
            qrModals1.value?.toggle()
          } else {
            Message.error(res.message)
          }
        })
      }
      // 序号	所属工厂	仓库编码	仓库名称	仓库地址	联系人	联系电话	操作
      const tableColumns = useTableColumn([
        {
          title: '布笼类型',
          key: 'clothType',
          dataIndex: 'clothType',
          slotName: 'clothType',
          width: 150,
        },
        {
          title: '公司',
          key: 'firm',
          dataIndex: 'firm',
          width: 150,
        },
        {
          title: '仓库名称',
          key: 'warehouseName',
          dataIndex: 'warehouseName',
          width: 150,
        },
        // {
        //     title: "所属区域",
        //     key: "areaName",
        //     dataIndex: "areaName",
        //     width: 150,
        // },
        {
          title: '布笼名称',
          key: 'shelveName',
          dataIndex: 'shelveName',
          width: 150,
        },
        {
          title: '编号',
          key: 'shelveCode',
          dataIndex: 'shelveCode',
          width: 150,
        },
        {
          title: '布笼二维码',
          key: 'qrcode',
          dataIndex: 'qrcode',
          slotName: 'qrcode',
          width: 150,
          fixed: 'right',
        },
        {
          title: '布笼一维码',
          key: 'barcode',
          dataIndex: 'barcode',
          slotName: 'barcode',
          width: 150,
          fixed: 'right',
        },
        // {
        //     title: "储位信息",
        //     key: "cw",
        //     dataIndex: "cw",
        //     slotName: 'cw',
        //     width: 150,
        //     fixed: 'right'
        // },
        {
          title: '备注',
          key: 'remark',
          dataIndex: 'remark',
          width: 150,
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 200,
        },
        {
          title: '修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 200,
        },
        {
          title: '操作',
          key: 'edit',
          dataIndex: 'edit',
          slotName: 'edit',
          width: 150,
          fixed: 'right',
        },
      ])
      let pageData: any = reactive({
        gcList: [],
        clothList: [],
        showAdd: false,
        warehouseName: [],
        shelveCode: [],
        pageLoading: false,
      })
      let pageData1 = reactive({
        sideTitle: '',
      })

      // onMounted(() => {
      //     doRefresh();
      // });
      const queryData = reactive({
        firmId: undefined,
        warehouseName: '',
        clothType: undefined,
      })
      let cklb = ref<any[]>([])
      const addHandler = () => {
        queryData.firmId = undefined
        queryData.warehouseName = ''
        ifalse.value = true
        pageData.showAdd = true
        pageData1.sideTitle = '新增布笼'
        for (let item in dataForm) {
          dataForm[item] = ''
        }
      }
      const casOb = ref()
      const xzgs = (val: any) => {
        dataForm.cklb = ''
        cklb.value = []
        dataForm.warehouseName = ''
        xzck.value = []

        setTimeout(function () {
          let list = casOb.value.selectViewValue[0]['label'].split('/')
          if (list.length > 1) {
            dataForm.firm = list[list.length - 1]
          } else {
            dataForm.firm = list[0]
          }
        }, 100)
      }
      const getAllTypeName = () => {
        dataForm.warehouseName = ''
        xzck.value = []
        post({
          url: 'wms/warehouseType/getWarehoursTypePara',
          data: {
            obsoleteState: 0,
          },
        }).then((res: any) => {
          if (res.code === 200) {
            cklb.value = res.data
          }
        })
      }
      const clearWarehouseChange = (val: any) => {
        dataForm.warehouseName = ''
        xzck.value = []
      }

      let xzck = ref<any[]>([])
      const xzlb = () => {
        if (dataForm.firmId == undefined || dataForm.firmId == 0 || dataForm.cklb == '') {
          xzck.value = []
          Message.warning('请先选择公司和仓库类型.')
          return
        }
        post({
          url: 'wms/warehouse/getWarehouseByPara',
          data: {
            firmId: dataForm.firmId,
            warehouseTypeName: dataForm.cklb,
            virtuallyState: 0,
          },
        }).then((res: any) => {
          if (res.code === 200) {
            xzck.value = res.data
          }
        })
      }
      let cwId = 0
      // const qyList: any = ref([])
      const xzckId = (val: any) => {
        xzck.value.forEach((item: any) => {
          if (item.warehouseName == dataForm.warehouseName) {
            cwId = item.id
          }
        })
      }
      const dataForm = reactive<chuwei>({
        id: '',
        firm: '',
        warehouseId: '',
        warehouseName: '',
        name: '',
        extendCode: '',
        cklb: '',
        shelveCode: '',
        shelveName: '',
        firmId: undefined,
        areaName: '',
        remark: '',
        clothType: 0,
        areaId: 0,
        shelveBarCode: '',
      })
      const formRef = ref<FormInstance>()
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            console.log(dataForm)
            let dataForms = {
              firm: dataForm.firm,
              clothType: dataForm.clothType,
              warehouseId: Number(cwId),
              warehouseName: dataForm.warehouseName,
              shelveName: dataForm.shelveName,
              shelveCode: dataForm.shelveCode,
              firmId: dataForm.firmId,
              remark: dataForm.remark,
              shelveBarCode: dataForm.shelveBarCode,
            }
            if (pageData1.sideTitle == '新增布笼') {
              post({
                url: 'wms/shelve/addShelve',
                data: [dataForms],
              }).then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  doRefresh()
                  pageData.showAdd = false
                  Message.success({
                    content: '添加成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
            } else if (pageData1.sideTitle == '修改布笼') {
              post({
                url: 'wms/shelve/updateShelve',
                data: [
                  {
                    id: dataForm.id,
                    shelveName: dataForm.shelveName,
                    shelveCode: dataForm.shelveCode,
                    remark: dataForm.remark,
                    shelveBarCode: dataForm.shelveBarCode,
                  },
                ],
              }).then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  doRefresh()
                  pageData.showAdd = false
                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
            }
          }
        })
      }
      // let gsData = ref<any[]>([])
      onMounted(() => {
        doRefresh()
        pageData2.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
        //弹出层的高
        if (pageData2.rHeight !== undefined) {
          pageData2.rHeight = pageData2.rHeight - 100
        }
      })
      const sideNo = () => {
        formRef.value?.resetFields()
        pageData.showAdd = false
      }
      let ifalse = ref(true)
      const editHandler = (key: any) => {
        ifalse.value = false
        dataForm.id = Number(key.id)
        dataForm.shelveName = key.shelveName
        dataForm.shelveCode = key.shelveCode
        dataForm.areaName = key.areaName
        dataForm.areaId = key.areaId
        dataForm.remark = key.remark
        dataForm.shelveBarCode = key.shelveBarCode
        dataForm.clothType = Number(key.clothType)
        pageData1.sideTitle = '修改布笼'
        pageData.showAdd = true
      }
      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          return
        }
        let asuiArray: any = []
        gridOption.value.getSelectedRows().forEach((item: any) => {
          asuiArray.push(Number(item.id))
        })
        let isArray: any[] = []
        gridOption.value.getSelectedRows().forEach((item: any) => {
          isArray.push(item.id)
        })

        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            // console.log(selectedRowKeys.value.values)
            post({
              url: 'wms/shelve/delShelve',
              data: asuiArray,
            }).then(({ code, data, message }: any) => {
              if (code === 200) {
                doRefresh()
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })
              } else {
                Message.error({
                  content: message,
                  duration: 5000,
                })
              }
            })
          },
        })
      }
      const print = () => {
        printJS({
          printable: 'htsts',
          type: 'html',
          targetStyles: ['*'],
        })
      }
      const print1 = () => {
        printJS({
          printable: 'hts',
          type: 'html',
          targetStyles: ['*'],
        })
      }
      const print2 = () => {
        printJS({
          printable: 'hts1',
          type: 'html',
          targetStyles: ['*'],
        })
      }
      const gbModal = () => {
        qrModal.value?.toggle()
      }
      const gbModals = () => {
        qrModals.value?.toggle()
      }
      const gbModals1 = () => {
        qrModals1.value?.toggle()
      }
      const selectHandler = () => {
        page.value = 1
        doRefresh()
      }
      const pageData2 = reactive<{
        showAdd: boolean
        rHeight: any
      }>({
        showAdd: false,
        rHeight: 0,
      })
      interface dataListType {
        storageName: any
        storageCode: any
      }
      const dataLists = ref<dataListType[]>([
        {
          storageName: '',
          storageCode: '',
        },
      ])
      const columns: any = [
        {
          title: '储位名称',
          dataIndex: 'storageName',
          slotName: 'storageName',
          width: 150,
        },
        {
          title: '储位自定义代号',
          dataIndex: 'storageCode',
          slotName: 'storageCode',
          width: 150,
        },
        {
          title: '储位二维码',
          key: 'qrcodes',
          dataIndex: 'qrcodes',
          slotName: 'qrcodes',
          width: 150,
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 200,
        },
        {
          title: '修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 200,
        },
        {
          title: '操作',
          dataIndex: 'save',
          slotName: 'save',
          fixed: 'right',
        },
      ]
      // const isHjZt = ref(false)
      const addHandler1 = () => {
        // isHjZt.value = true
        // ztPd.value = false
        if (dataLists.value.length > lengsDs) {
          Message.warning('请先保存后在添加')
          return
        } else {
          dataLists.value.push({
            storageName: '',
            storageCode: '',
          })
        }
      }
      let keyList = {
        shelveId: 0,
        shelveName: '',
      }
      interface keyscwType {
        firm: any
        warehouseId: any
        warehouseName: any
        id: any
        name: any
        shelveName: any
      }
      let keyscw: keyscwType = {
        firm: '',
        warehouseId: '',
        warehouseName: '',
        id: '',
        name: '',
        shelveName: '',
      }
      const editHandler1 = (key: any) => {
        keyList.shelveId = Number(key.id)
        keyList.shelveName = key.name
        opCwdata(keyList)
        keyscw = key
        pageData2.showAdd = true
      }

      let lengsDs: number = 0

      function opCwdata(key: any) {
        post({
          url: 'wms/Storage/getStorageByPara',
          data: key,
        })
          .then((res: any) => {
            if (res.code === 200) {
              dataLists.value = res.data
              lengsDs = res.data.length
              console.log(res.data)
            }
          })
          .catch(console.log)
      }
      const sideNo1 = () => {
        pageData2.showAdd = false
      }
      const bcCw = (key: any) => {
        if (key.createName) {
          Message.warning('该储位已存在只能修改或删除！')
          return
        } else {
          let cw = {
            firm: keyscw.firm,
            warehouseId: Number(keyscw.warehouseId),
            warehouseName: keyscw.warehouseName,
            shelveId: Number(keyscw.id),
            shelveName: keyscw.shelveName,
            storageName: key.storageName,
            storageCode: key.storageCode,
          }
          post({
            url: 'wms/Storage/addStorage',
            data: [cw],
          }).then((res: any) => {
            if (res.code === 200) {
              // isHjZt.value = false
              opCwdata(keyList)
              Message.success('保存成功')
            } else {
              Message.error(res.message)
            }
          })
        }
      }
      const bcCw1 = (key: any) => {
        // isHjZt.value = true
        if (key.createName) {
          post({
            url: 'wms/Storage/updateStorage',
            data: [
              {
                id: Number(key.id),
                storageName: key.storageName,
                storageCode: key.storageCode,
              },
            ],
          }).then((res: any) => {
            if (res.code === 200) {
              // isHjZt.value = false
              opCwdata(keyList)
              Message.success('修改成功')
            } else {
              Message.error(res.message)
            }
          })
        } else {
          Message.error('该储位不存在，请保存后在修改!')
          return
        }
      }
      let selectedRowKeys1 = ref([])
      const delcwTab = () => {
        if (selectedRowKeys1.value.length === 0) {
          return
        }
        let isArray: any = []
        selectedRowKeys1.value.forEach((item) => {
          isArray.push(Number(item))
        })
        console.log(isArray)
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            // console.log(selectedRowKeys.value.values)
            post({
              url: 'wms/Storage/delStorage',
              data: isArray,
            }).then(({ code, data, message }: any) => {
              if (code === 200) {
                opCwdata(keyList)
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })
              } else {
                Message.error({
                  content: message,
                  duration: 5000,
                })
              }
            })
          },
        })
      }
      const inputBlur = () => {
        dataForm.shelveCode = dataForm.shelveCode.toUpperCase()
      }

      const options = ref<any>(pageData.warehouseName)
      // const options1 = ref<any>(pageData.shelveCode);
      const loading = ref(false)
      // const loading1 = ref(false);
      const handleSearch = (value: any) => {
        if (value) {
          const ob = { warehouseName: value }
          loading.value = true
          window.setTimeout(() => {
            selCxAll(ob)
            options.value = pageData.warehouseName
            loading.value = false
          }, 100)
        } else {
          options.value = []
        }
      }
      function selCxAll(val: any) {
        post({
          url: 'wms/warehouse/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            console.log(data)
            pageData.warehouseName = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      const handleSearchs = () => {
        if (queryData.firmId == undefined || queryData.firmId == '') {
          pageData.warehouseName = []
          Message.warning('请先选择公司')
          return
        }
        post({
          url: 'wms/warehouse/getWarehouseByPara',
          data: {
            firmId: queryData.firmId,
            virtuallyState: 0,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            pageData.warehouseName = res.data
          } else {
            Message.error(res.message)
          }
        })
      }

      const exports = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.warning('请先勾选')
          return
        } else {
          //将表头拼接出来
          let head =
            '<th>布笼类型</th><th>公司</th><th>仓库名称</th><th>布笼名称</th><th>编号</th><th>备注</th><th>创建人</th><th>创建时间</th><th>修改人</th><th>修改时间</th>'
          //拿到当前表格数据与勾选的行做筛选

          let nowRow = table.dataList.filter(function (o) {
            return (
              gridOption.value
                .getSelectedRows()
                .map((o: any) => {
                  return o.id
                })
                .indexOf(o['id']) !== -1
            )
          })
          let body = ''
          nowRow.forEach(function (o) {
            body += '<tr><td>' + (o['clothType'] == 0 ? '通用布笼' : '固定布笼') + '</td>'
            body += '<td>' + o['firm'] + '</td>'
            body += '<td>' + o['warehouseName'] + '</td>'
            body += '<td>' + o['shelveName'] + '</td>'
            body += '<td>' + o['shelveCode'] + '</td>'
            body += '<td>' + o['remark'] + '</td>'
            body += '<td>' + o['createName'] + '</td>'
            body += '<td>' + o['createTime'] + '</td>'
            body += '<td>' + o['updateName'] + '</td>'
            body += '<td>' + o['updateTime'] + '</td>'
            body += '</tr>'
          })
          tableToXlsx(head, '布笼', body)
        }
      }

      function tableToXlsx(head: any, filename: any, body: any) {
        const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

        const a = document.createElement('a')
        a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
        a.download = filename
        a.click()
        document.removeChild(a)
      }
      const isChiese = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值不能包含中文！')
          }
          resolve()
        })
      }
      const isNumber = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          var isletter = /^[0-9]+$/.test(value)
          if (!isletter) {
            cb('填写的值必须为数字！')
          }
          resolve()
        })
      }
      const headerShow = ref<boolean>(true)

      let gsDatas = ref<any[]>([])
      // 获取公司下拉框
      const getAllActiveCompany = () => {
        post({
          url: 'org/baCompany/getTreeCompanyByUser',
          data: {},
        }).then((result: any) => {
          if (result.code === 200) {
            gsDatas.value = result.data
          } else {
            Message.error(result.message)
          }
        })
      }
      const queryClearChange = () => {
        pageData.warehouseName = []
        queryData.warehouseName = ''
      }
      const clothTypeChange = () => {
        if (dataForm.clothType == 0) {
          ifalse.value = false
          dataForm.firmId = undefined
          dataForm.firm = ''
          gsDatas.value = []
          dataForm.cklb = ''
          cklb.value = []
          dataForm.warehouseName = ''
          xzck.value = []
        } else {
          ifalse.value = true
          getAllActiveCompany()
          getAllTypeName()
        }
      }
      const gridOption = ref()
      const colState = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        colState.value = params.columnApi
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
      }
      let tc: any[] = tableColumns.map((o: any) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          width: 150,
        }
        if (o.slotName === 'edit') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 150
          obj['cellRenderer'] = {
            template: `
                    <a-space>
                        <a-button type="primary" size="small" status="warning" @click="a1">
                            <template #icon>
                                <icon-edit />
                            </template>
                            修 改
                        </a-button>
                    </a-space>

                    `,
            setup(props: any) {
              const isDtas = ref(props.params.data)
              const a1 = () => {
                editHandler(props.params.data)
              }
              return {
                a1,
                isDtas,
              }
            },
          }
        }
        if (o.slotName === 'cw') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 150
          obj['cellRenderer'] = {
            template: `
                    <a-space>
                        <a-button type="primary" @click="a1">储位</a-button>
                    </a-space>

                    `,
            setup(props: any) {
              const isDtas = ref(props.params.data)
              const a1 = () => {
                console.log(1111111111)
                editHandler1(props.params.data)
              }
              return {
                a1,
                isDtas,
              }
            },
          }
        }
        if (o.slotName === 'qrcode') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 150
          obj['cellRenderer'] = {
            template: `
                    <a-space>
                        <a-button v-if="e" status="success" @click="a1">查看二维码</a-button>
                    </a-space>
                    `,
            setup(props: any) {
              const isDtas = ref(props.params.data)
              const a1 = () => {
                openQRcode(props.params.data)
              }
              return {
                a1,
                isDtas,
                e: permissionStore.hasPermisson('blxx.cckewm'),
              }
            },
          }
        }
        if (o.slotName === 'barcode') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 150
          obj['cellRenderer'] = {
            template: `
                    <a-space>
                        <a-button v-if="e" status="success" @click="a1">查看一维码</a-button>
                    </a-space>
                    `,
            setup(props: any) {
              const isDtas = ref(props.params.data)
              const a1 = () => {
                openBarcode(props.params.data)
              }
              return {
                a1,
                isDtas,
                e: permissionStore.hasPermisson('blxx.cckewm'),
              }
            },
          }
        }
        if (o.slotName === 'clothType') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['cellRenderer'] = {
            template: `
                          <a-tag color="#ff7d00" v-if="params.data.clothType==0">{{val}}</a-tag>
                          <a-tag color="green" v-else>{{val}}</a-tag>`,
            setup(props: any) {
              let val = ref()
              if (props.params.data.clothType == 0) {
                val.value = '通用布笼'
              } else {
                val.value = '固定布笼'
              }
              return {
                val,
              }
            },
          }
        }
        return obj
      })

      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      const localeText1: any = ref(localeText)
      const pagingList1: any = ref(pagingList)
      const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
        saveOrUpdateGridState01('AstorageShelf-1', gridOption, colState, tc)
      const onColumnMoved = () => {
        saveGridState01()
      }
      const onColumnResized = () => {
        saveGridState01()
      }
      const onColumnVisible = () => {
        saveGridState01()
      }
      // 通用布笼模板下载
      const tyblmbxzs = () => {
        axios
          .get(baseURL + '/wms/shelve/uploadModel', {
            responseType: 'blob',
            headers: {
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((res) => {
            if (res.status === 200) {
              filedownload(res.data, '通用布笼导入模板.xlsx')
            }
          })
      }
      //导入
      const importHandler = () => {
        const inputEle: HTMLInputElement = document.createElement('input')
        inputEle.type = 'file'
        inputEle.id = 'fileUploadExcel'
        inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
        inputEle.addEventListener('change', (e) => {
          const formData = new FormData()
          if (inputEle.files !== null) {
            formData.append('file', inputEle.files[0] || '')
          } else {
            Message.warning('未选择文件！')
            return
          }
          pageData.pageLoading = true
          axios
            .post(baseURL + '/wms/shelve/importModelData', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((result) => {
              if (result.data['code'] === 200) {
                Message.success('导入成功')
              } else {
                Message.error(result.data.message)
              }
            })
            .finally(() => {
              pageData.pageLoading = false
              doRefresh()
            })
        })
        inputEle.click()
      }
      return {
        importHandler,
        tyblmbxzs,
        saveOrUpdateGridState01,
        saveGridState01,
        updateGridState01,
        onColumnMoved,
        onColumnResized,
        onColumnVisible,
        colState,
        pagingList1,
        localeText1,
        change1,
        PageSize,
        total,
        page,
        size,
        tc,
        defaultColDef,
        gridReady,
        gridOption,
        // isHjZt,
        getAllActiveCompany,
        headerShow,
        isChiese,
        print2,
        print1,
        gbModals1,
        openQRcodes1,
        qrDatas1,
        gbModals,
        qrModals,
        qrDatas,
        handleSearchs,
        exports,
        options,
        // options1,
        loading,
        // loading1,
        handleSearch,
        // handleSearch1,
        inputBlur,
        delcwTab,
        selectedRowKeys1,
        bcCw1,
        bcCw,
        columns,
        addHandler1,
        dataLists,
        sideNo1,
        pageData2,
        editHandler1,
        ifalse,
        selectHandler,
        gbModal,
        print,
        // dataList,
        editHandler,
        sideNo,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        qrModal,
        qrData,
        openQRcode,
        validateIdCheck,
        xzgs,
        cklb,
        xzlb,
        xzck,
        xzckId,
        pageData1,
        gsDatas,
        openQRcodes,
        qrModals1,
        casOb,
        queryClearChange,
        getAllTypeName,
        clearWarehouseChange,
        clothTypeChange,
        permissionStore,
        isNumber,
        visible,
        modalData,
        modalOk,
        modalCancel,
      }
    },
    components: { Toolbar, QrcodeVue, ModalDialog, oneCode },
  }
</script>
<style scoped lang="less">
  .selectCc {
    width: 100%;
    text-align: right;
    margin-right: 20px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }

  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }
</style>
